package com.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import java.util.Random;

@Aspect
@Component
public class AppAspect {
    // 定义切点，匹配 OrderService 接口的所有方法
    @Pointcut("execution(* com.service.AppService.*(..))")
    public void orderPointcut() {}

    // 前置增强
    @Before("orderPointcut()")
    public void beforeAdvice(JoinPoint joinPoint) {
        System.out.println("hello, 我是一个前置增强");
    }

    // 后置增强（方法正常执行完后）
    @AfterReturning("execution(* com.service.AppService.add(..)) || execution(* com.service.AppService.delete(..))")
    public void afterReturningAdvice() {
        System.out.println("bye, 我是一个后置增强");
    }

    // 获取方法返回值并输出
    @AfterReturning(pointcut = "orderPointcut()", returning = "result")
    public void afterReturningWithResultAdvice(JoinPoint joinPoint, Object result) {
        String methodName = joinPoint.getSignature().getName();
        System.out.println(methodName + " 方法的返回值为: " + result);
    }

    // 输出方法执行时间
    @Around("orderPointcut()")
    public Object aroundAdvice(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object result = proceedingJoinPoint.proceed();
        long endTime = System.currentTimeMillis();
        String methodName = proceedingJoinPoint.getSignature().getName();
        System.out.println(methodName + " 方法执行时间为: " + (endTime - startTime) + " 毫秒");
        return result;
    }

    // 权限检验（针对 add 和 delete 方法）
    @Before("execution(* com.service.AppService.add(..)) || execution(* com.service.AppService.delete(..))")
    public void checkPermission(JoinPoint joinPoint) throws Throwable {
        Random random = new Random();
        int permission = random.nextInt(2);
        if (permission == 0) {
            System.out.println("有权限，允许执行 " + joinPoint.getSignature().getName() + " 方法");
        } else {
            System.out.println("没有权限，终止 " + joinPoint.getSignature().getName() + " 方法的运行");
            // 这里通过抛异常来终止方法运行，实际项目中可根据情况选择合适的方式
            throw new RuntimeException("没有权限执行该操作");
        }
    }
}
